package com.yunfeisoft.business.dao.impl;

import com.yunfeisoft.base.model.Organization;
import com.yunfeisoft.business.dao.inter.ElderDao;
import com.yunfeisoft.business.model.Elder;
import com.yunfeisoft.business.model.ElderApprovalResult;
import com.yunfeisoft.common.base.BaseDaoImpl;
import com.yunfeisoft.common.sql.builder.SelectBuilder;
import com.yunfeisoft.common.sql.builder.WhereBuilder;
import com.yunfeisoft.common.utils.Page;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;

/**
 * ClassName: ElderDaoImpl
 * Description: 老人入院登记表Dao实现
 * Author: Jackie liu
 * Date: 2020-01-13
 */
@Repository
public class ElderDaoImpl extends BaseDaoImpl<Elder, String> implements ElderDao {

    @Override
    public Page<Elder> queryPage(Map<String, Object> params) {
        WhereBuilder wb = new WhereBuilder();
        wb.setOrderByWithDesc("e.createTime");
        if (params != null) {
            initPageParam(wb, params);
            wb.andEquals("e.status", params.get("status"));
            wb.andEquals("e.orgId", params.get("orgId"));
            wb.andEquals("e.nursingLevel", params.get("nursingLevel"));
            wb.andFullLike("e.name", params.get("name"));
            // 如果是入院登记，即status=1时，才需要关联创建人
            if (ObjectUtils.isEmpty(params.get("status"))) {
                wb.andEquals("e.createId", params.get("createId"));
            }
        }

        SelectBuilder builder = getSelectBuilder("e");
        builder.column("org.name as orgName")
                .leftJoin(Organization.class).alias("org").on("e.orgId = org.id").build();

        return queryPage(builder.getSql(), wb);
    }

    /**
     * 分页查询我的审批列表
     *
     * @param params
     * @return
     */
    @Override
    public Page<Elder> myApprovalList(Map<String, Object> params) {
        WhereBuilder wb = new WhereBuilder();
        if (params != null) {
            initPageParam(wb, params);
            wb.andEquals("status", params.get("status"));
            wb.andEquals("nursingLevel", params.get("nursingLevel"));
            wb.andFullLike("name", params.get("name"));
            wb.andEquals("r.createId", params.get("createId"));
        }
        SelectBuilder builder = getSelectBuilder("e");
        builder.column("r.status as approvalStatus")
                .column("r.createTime as approvalCreateTime")
                .leftJoin(ElderApprovalResult.class)
                .alias("r")
                .on("e.id = r.elderId")
                .build();
        wb.setOrderByWithDesc("r.createTime");
        return queryPage(builder.getSql(), wb);
    }

    @Override
    public List<Elder> listAll(Map<String, Object> params) {
        WhereBuilder wb = new WhereBuilder();
        if (!ObjectUtils.isEmpty(params.get("name"))) {
            wb.andFullLike("name", params.get("name"));
        }
        return query(wb);
    }
}